<script setup>
import Viewer from '@src/Map/map';
import Request from '../request';
import { myToken } from '@src/config/sysConfig';
import { onMounted, reactive, ref, watch } from 'vue';
// 流线
import img from './gyLine/line.png';
import './gyLine/PolylineTrailMaterialProperty';

//水流
import movingRiver from './assets/movingRiver.png';

// 乌云及雨
// import RainCloud from './rainCloud/cloud';
// import Rain from './rainCloud/rain';

//产品图
// import areaImg0 from './assets/area0.png';
import areaImg from './assets/area.png';
import transparentImg from './assets/transparent.png';

//雷达图
import RadarSail from './radar/radarSail';

let viewer;
let entitiesMap = new Map();
let cruise;

const map = reactive({
  layerInfoAry: [],
  layerID: 'tdt-img',
  isFollow: false,
});

const selectValue = ref('');
const options = [
  //   {
  //     value: 'Img0',
  //     label: '产品图(未裁剪)',
  //     disabled: true,
  //   },
  {
    value: 'Img1',
    label: '产品图(行政区裁剪)',
  },
  {
    value: 'Trail',
    label: '流线',
  },
  {
    value: 'Water',
    label: '河面水流',
  },
  {
    value: 'Rader',
    label: '雷达图',
  },
];

watch(
  () => selectValue.value,
  (v) => {
    switch (v) {
      case 'Img0':
        addImg(true);
        break;
      case 'Img1':
        addImg(false);
        break;
      case 'Trail':
        // 添加流线
        addTrail();
        break;
      case 'Water':
        // 添加水流
        addWater();
        break;
      case 'Rader':
        // 雷达
        addRader();
        break;
      default:
        break;
    }
  }
);

onMounted(() => {
  Request.getJson('./config/mapCfg.json', (r) => {
    viewer = new Viewer(
      'mapContainer',
      [116.3677, 39.9041, 3566, 10, -28, 0],
      //   [118.8627, 33.0128, 1e6, 0, -90, 0],
      true,
      r,
      myToken,
      0
    );
    // 图层下拉
    map.layerInfoAry = viewer.layerInfoAry;

    selectValue.value = 'Rader';

    /**************** webGL相关 ****************/
    //查看内置vs,fs
    // console.log(new Cesium.EllipsoidSurfaceAppearance({}));

    //查看自定义Material
    // console.log(new Cesium.Material({}));

    //查看内置materials
    // console.log(Cesium.Material._materialCache._materials);

    //步步深入
    //Image(图形透明度+裁剪原理)
    // addImg();

    // 添加流线
    // addTrail();

    // 添加水流
    // addWater();

    // 雷达
    // addRader();

    //下雨场景
    // addRainCloud();

    /**************** 时钟相关 ****************/

    //巡航
    // addCruise();
  });
});

//图片加载（透明度+裁切）
const addImg = (isEntity = true) => {
  const { Rectangle, ImageMaterialProperty, Color, CallbackProperty } = Cesium;
  const SJZextend = [
    //石家庄四角坐标
    113.51657923826986, 37.43655337821605, 115.362312014488, 38.763596488890926,
  ];
  const initPosition = [
    114.41052154857562, 38.13588306365133, 374212.5412589345, 0, -90, 0,
  ]; //石家庄
  viewer.setView(initPosition, 0);

  if (isEntity) {
    viewer.entities.add({
      id: 'img',
      name: 'img-entity',
      rectangle: {
        coordinates: Rectangle.fromDegrees(...SJZextend),
        //ImageMaterialProperty映射Materials-Image
        material: new ImageMaterialProperty({
          image: transparentImg,
          color: Color.WHITE.withAlpha(0.8),
        }),
      },
    });
  } else {
    const p = viewer.scene.primitives.add(
      new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
          geometry: new Cesium.RectangleGeometry({
            rectangle: Rectangle.fromDegrees(...SJZextend),
            vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
          }),
        }),
        appearance: new Cesium.EllipsoidSurfaceAppearance({
          material: new Cesium.Material({
            fabric: {
              type: 'Image',
              uniforms: {
                image: transparentImg,
                areaImage: areaImg,
                color: Color.WHITE.withAlpha(0.8),
              },
              source: `czm_material czm_getMaterial(czm_materialInput materialInput)
              {
                  czm_material material = czm_getDefaultMaterial(materialInput);
                  vec2 st = materialInput.st;
                  vec4 colorImage = texture2D(image,vec2(st.s, st.t));
                  vec4 areaImage = texture2D(areaImage,vec2(st.s, st.t));
                  material.alpha = colorImage.a * areaImage.a * color.a;
                  material.diffuse = colorImage.rgb;
                  return material;
              }
              `,
            },
          }),
        }),
      })
    );
    // console.log(p.appearance.material);
  }
};

// 添加流线
const addTrail = () => {
  const initPosition = [116.3677, 39.9041, 3566, 10, -28, 0]; //石家庄
  viewer.setView(initPosition, 0);
  const polylineArr = [
    116.36578323959371, 39.94717447037612, 0, 116.40200620078545,
    39.94788986593708, 10000, 116.40126332543285, 39.9870228957151, 0,
    116.36315522148672, 39.985919757736404, 0, 116.36578323959371,
    39.94717447037612, 0,
  ];
  const isEntity = false;
  const color = Cesium.Color.CYAN;
  if (isEntity) {
    const trail = viewer.entities.add({
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(polylineArr),
        width: 20,
        material: new Cesium.PolylineTrailMaterialProperty({
          color,
          duration: 3000,
          trailImage: img,
        }),
      },
    });
    entitiesMap.set('polylineTrail', trail);
  } else {
    const geometryInstances = new Cesium.GeometryInstance({
      geometry: new Cesium.GroundPolylineGeometry({
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(polylineArr),
        width: 20,
        vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
      }),
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          Cesium.Color.WHITE
        ),
      },
    });
    const trailPrimitive = new Cesium.GroundPolylinePrimitive({
      geometryInstances,
      appearance: new Cesium.PolylineMaterialAppearance({
        material: new Cesium.Material({
          fabric: {
            uniforms: {
              image: img,
              color,
              repeat: 1,
              animationSpeed: 0.01,
              // pixelOffset: new Cesium.Cartesian2(0, 150),
            },
            source:
              'czm_material czm_getMaterial(czm_materialInput materialInput) { \n\
                czm_material material = czm_getDefaultMaterial(materialInput);\n\
                vec2 st = materialInput.st * repeat;\n\
                float time = czm_frameNumber * animationSpeed;\n\
                vec4 colorImage = texture2D(image,vec2(fract(st.s - time), st.t));\n\
                material.alpha = colorImage.a;\n\
                material.diffuse = color.rgb;\n\
                return material;\n\
                } \n',
          },
        }),
      }),
      asynchronous: true,
    });
    viewer.scene.primitives.add(trailPrimitive);
  }
};

//添加水流
const addWater = () => {
  const initPosition = [116.3677, 39.9041, 3566, 10, -28, 0]; //石家庄
  viewer.setView(initPosition, 0);

  const polylineArr = [
    116.36578323959371, 39.94717447037612, 0, 116.40200620078545,
    39.94788986593708, 0, 116.40126332543285, 39.9870228957151, 0,
    116.36315522148672, 39.985919757736404, 0, 116.36578323959371,
    39.94717447037612, 0,
  ];
  let polygonGeometry = new Cesium.PolygonGeometry({
    polygonHierarchy: new Cesium.PolygonHierarchy(
      Cesium.Cartesian3.fromDegreesArrayHeights(polylineArr)
    ),
    height: 0,
    id: 'PolygonGeometry',
  });
  viewer.scene.primitives.add(
    new Cesium.Primitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: polygonGeometry,
      }),
      appearance: new Cesium.EllipsoidSurfaceAppearance({
        material: new Cesium.Material({
          fabric: {
            uniforms: {
              image: movingRiver,
              animationSpeed: 0.002,
              alpha: 0.8,
              //   color: new Cesium.Color(1.0, 1.0, 1.0, 1),
            },
            source:
              'czm_material czm_getMaterial(czm_materialInput materialInput)\n\
          {\n\
                czm_material material = czm_getDefaultMaterial(materialInput);\n\
                vec2 st = materialInput.st;\n\
                float time = czm_frameNumber * animationSpeed;\n\
                vec4 colorImage = texture2D(image, vec2(fract(st.s - time), st.t));\n\
                material.alpha = alpha;\n\
                material.diffuse = colorImage.rgb;\n\
                // material.diffuse = (colorImage.rgb+color.rgb)/2.0;\n\
                return material;\n\
            }',
          },
        }),
        aboveGround: false,
      }),
    })
  );
};

//添加雷达图
//自定义三角形参考链接：https://blog.csdn.net/liguoweioo/article/details/120541359
const addRader = () => {
  Request.getJson('./data/city/radarData.json', (dataRadar) => {
    const valueRadar = [0, 20, 40, 60, 80, 100];
    const radarZoom = 25000;
    const radarSail = new RadarSail(viewer, 0.55);
    radarSail.doLoadData(dataRadar, valueRadar);
    radarSail.zoomToThis(radarZoom);
    radarSail.changShowSail(true);
  });
};

//下雨场景
const addRainCloud = () => {
  const cloudCTT = new RainCloud(viewer);
  Request.getJson('./data/city/yun2.json', (res) => {
    cloudCTT.loadDataInfo(res);
    if (cloudCTT.isLoadData) {
      cloudCTT.renderCloudCTT(true);
      cloudCTT.changeShow(true);
    }
  });
  const rain = new Rain(viewer);
  rain.show();
  //   viewer.setView([116.3677, 39.9041, 2000, -90, -20, 0], 0);
};

// 底图切换
watch(
  () => map.layerID,
  () => {
    const layerID = map.layerID;
    if (layerID) {
      viewer.switchLayer(layerID, layerID + '-label');
    }
  }
);

// 巡航跟踪
function lookFly() {
  // 用相机跟随模型
  if (map.isFollow) {
    map.isFollow = false;
    cruise.changeEyeAngle('third');
    // cruise.lookFly(false)
  } else {
    map.isFollow = true;
    cruise.changeEyeAngle('first');
    // cruise.lookFly(true)
  }
}
</script>

<template>
  <div id="C">
    <el-select v-model="selectValue"
               placeholder="Select">
      <el-option v-for="item in options"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value"
                 :disabled="item.disabled" />
    </el-select>
    <div id="mapContainer" />
    <!-- <div id='operate'>
      <el-button @click="lookFly">{{ map.isFollow?'取消跟随':'跟随飞机'}}</el-button>
      <el-select v-model="map.layerID">
        <template v-for="item in map.layerInfoAry"
                  :key="item.id">
          <el-option v-if="!item.isLabel"
                     :label="item.name"
                     :value="item.id" />
        </template>
      </el-select>
    </div> -->
  </div>
</template>

<style lang="scss">
#C {
  width: 100%;
  height: 100%;
  //   position: absolute;
  overflow: hidden;

  .el-select {
    position: absolute;
    margin: 20px;
    z-index: 2;
  }

  #mapContainer {
    width: 100%;
    height: 100%;
    .cesium-widget canvas {
      width: 100%;
      height: 100%;
      position: absolute;
    }
  }

  #operate {
    position: absolute;
    z-index: 2;
    display: flex;
    flex-direction: column;
    row-gap: 10px;
    padding: 10px;
    width: 150px;
  }
}
</style>
